const fs = require('fs');
const crypto = require('crypto');
const querystring = require('querystring');

// 将 JSON 数据转换为字符串
const jsonString = fs.readFileSync('D:\\华为家庭存储\\PrivateSpace\\Audiovisual\\index.json').toString();

// 选择加密算法
const algorithm = 'aes-256-cbc';

// 生成密钥和初始化向量
const key = crypto.randomBytes(32); // 32 字节的密钥
const iv = crypto.randomBytes(16); // 16 字节的初始化向量

// 加密 JSON 字符串
function encryptData(data, key, iv) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(data, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return { encrypted, key: key.toString('hex'), iv: iv.toString('hex') };
}

// 解密加密后的数据
function decryptData(encrypted, key, iv) {
  const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key, 'hex'), Buffer.from(iv, 'hex'));
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

// 加密 JSON 数据
const { encrypted, key: hexKey, iv: hexIV } = encryptData(jsonString, key, iv);

// 拼接成链接地址
const query = querystring.stringify({
  encrypted,
  key: hexKey,
  iv: hexIV,
});

fs.writeFileSync('D:\\ZiShenKongJian\\rml-backups\\华为备忘录\\加密JSON内容为字符串\\encrypted.txt', query);
console.log('加密后的链接:', query);

// 解密示例
const urlParams = new URLSearchParams(query);
const encryptedData = urlParams.get('encrypted');
const keyData = urlParams.get('key');
const ivData = urlParams.get('iv');

if (encryptedData && keyData && ivData) {
  const decryptedData = decryptData(encryptedData, keyData, ivData);
  console.log('解密后的 JSON 数据:', decryptedData);
}
